package com.bjpower.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.bjpower.models.request.PayWayInfoRequest;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.TreeMap;


public class CheckSign {

    public  static Boolean checkSign(PayWayInfoRequest payWayInfoRequest , String originSign , String appSecret){
        String jsonStr = JSONUtil.toJsonStr(payWayInfoRequest);
        Map paramMap = JSONUtil.toBean(jsonStr, Map.class);
        //去掉请求中的sign
        paramMap.remove("sign");

        //使用TreeMap 默认就是字典排序
        TreeMap<String,String> treeMap = new TreeMap<>(paramMap);

        //将非空参数连接为 参数1=值1&参数2=值2
        StringBuilder builder = new StringBuilder();
        treeMap.forEach( (k,v)->{
            if(StrUtil.isNotBlank(v)){
                builder.append(k).append("=").append(v).append("&");
            }
        });
        //"&appSecret=分配的密钥"
        builder.append("appSecret").append("=").append(appSecret);
        //使用md5处理后
        String sign = DigestUtil.md5Hex(builder.toString());

        //true：请求签名正确
        return sign.equals(originSign);

    }

}
